﻿using System.Collections.Generic;
using UnityEngine;

public class SlicedTarget : MonoBehaviour {
    static readonly List<SlicedTarget> _targets = new List<SlicedTarget>();

    public static IList<SlicedTarget> Targets {
        get { return _targets.AsReadOnly(); }
    }

    static float _volumeThreshold;

    [HideInInspector]
    public new Transform transform;

    [HideInInspector]
    public new Collider collider;

    public bool CanSlice {
        get {
            var mesh = GetComponent<MeshFilter>().mesh;
            var size = mesh.bounds.size;
            var volume = size.x * size.y * size.z;
            return volume >= _volumeThreshold;
        }
    }

    void Awake() {
        transform = GetComponent<Transform>();
        collider = GetComponent<Collider>();
    }
	
    void OnEnable() {
        _targets.Add(this);
    }

    void OnDisable() {
        _targets.Remove(this);
    }

    public static void Clear() {
        for (var i = _targets.Count - 1; i >= 0; i--) {
            _targets[i].RemoveSelf();
        }
    }

    public void RemoveSelf() {
        Destroy(this);
    }

    public void AddPhysicMaterial() {
        collider.material = ChineseRestaurantManager.Instance.PhysicMat;
    }

    public static void AttachTo(GameObject go) {
        go.AddComponent<SlicedTarget>();
        var size = go.GetComponent<MeshFilter>().mesh.bounds.size;
        var volume = size.x * size.y * size.z;
        _volumeThreshold = volume / (TargetSlicer.Instance.sampleCount + 1);
    }
}
